package cn.yj.netty.support.test;

import cn.yj.netty.common.Const;
import cn.yj.netty.common.Encrypt;
import cn.yj.netty.support.test.protocol.Header;
import cn.yj.netty.utils.EncryptionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.lang.reflect.Field;

/**
 * 编码器
 * @author 永健
 * @since 2022-02-15 20:22
 */
public class MessageEncode extends MessageToByteEncoder<MessageProtocol> {

    @Override
    protected void encode(ChannelHandlerContext ctx, MessageProtocol msg, ByteBuf out) throws Exception {
        Header header = msg.getHeader();

        // body 是否要加密
        if (Encrypt.YES.getCode().equals(header.getEncode())) {
            msg.setBody(EncryptionUtils.encrypt(msg.getBody()));
        }

        StringBuilder buffer = new StringBuilder();
        buffer.append(Const.DELIMITER_START).append("\n");
        Field[] declaredFields = header.getClass().getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            try {
                Object value = declaredField.get(header);
                buffer.append(name).append(":").append(value != null? value.toString() : "").append("\n");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        buffer.append("\n");
        buffer.append("body:" + msg.getBody());
        buffer.append("\n");
        buffer.append(Const.DELIMITER_END);
        out.writeBytes(buffer.toString().getBytes(msg.getHeader().getEncode()));
    }
}
